package org.example.classtopia.scheduler;

import org.example.classtopia.Service.CourseService;
import org.example.classtopia.Service.UserService;
import org.example.classtopia.Utils.DateUtils; // 导入DateUtils
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; // 导入Value注解
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class ScheduleReminderTask {

    @Autowired
    private CourseService courseService;

    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(ScheduleReminderTask.class);

    // 从配置文件中读取当前学期开始日期，或者从数据库动态获取
    @Value("${classtopia.current-semester:2025-06-23}") // 示例，提供默认值
    private String currentSemesterStartDate;

    @Scheduled(cron = "0 */5 * * * ?") // 建议改为每5分钟执行一次，避免频繁扫描
    public void sendReminders() {
        LocalDate today = LocalDate.now();
        // 使用 DateUtils 计算当前周次
        int currentWeek = DateUtils.calculateCurrentWeek(currentSemesterStartDate, today);
        int currentDay = today.getDayOfWeek().getValue(); // 1=周一，7=周日


        logger.info("定时任务触发，时间={}，学期={}，当前日期={}，周次={}，星期={}",
                LocalDateTime.now(), currentSemesterStartDate, today, currentWeek, currentDay);
        // 优化点：只获取今天有日程的用户ID，而不是所有用户
        // 假设userService.getUsersWithSchedulesToday 方法已实现，
        // 能够根据当前日期和周次找到当天有日程的用户ID列表
        //List<Long> userIdsToRemind = userService.getUsersWithSchedulesToday(currentSemesterStartDate, currentWeek, currentDay);

        // 如果没有这个优化，仍然是获取所有用户
         List<Long> allUserIds = userService.getAllUserIds();
         List<Long> userIdsToRemind = allUserIds; // 暂时用全部用户

        logger.info("获取用户总数: {}", allUserIds.size());

        for (Long userId : userIdsToRemind) {
            logger.debug("处理用户ID: {}", userId);
            // 调用服务层发送提醒，注意这里传入的是读取到的学期开始日期字符串
            courseService.sendTodayScheduleReminders(userId, currentSemesterStartDate, currentWeek, currentDay);
        }
    }

    // 移除私有方法 calculateCurrentWeek
}


